#!/usr/bin/python
# -*- coding: UTF-8 -*- 

import os, re

folder_path = "dictionary/zh_symbol/"

def find_and_replace(srcpairs, vowel, change, expression, file_target):
	respairs = []

	for pairs in srcpairs:
		key = pairs[0]

		match = re.findall(expression, key)
		if len(match) == 0:
			respairs.append(pairs)
		else:
			tone = int(key[-1])
			pinyin = key[:-1]
			pinyin = pinyin.replace(vowel, change[tone-1])

			if(pinyin[-1] == "r"):	#去掉er
				if(key!="er1" and key!="er2" and key!="er3" and key!="er4" and key!="er5"):
					continue
				else:
					print("剔除儿化音:", key)

			#iu标在u上
			if(vowel == "i" and key[-2]=="u"):
				print("剔除错误的iu组合：", pinyin, key)
				respairs.append(pairs)
				continue

			newline = pinyin + "\t" + pairs[1] + " " + pairs[2]
			file_target.write(newline + "\n")

	return respairs


############################################
if __name__=="__main__":
	src_pairs = []
	with open(os.path.join(folder_path, "simple.lexicon"), "r") as fSrc:
		for line in fSrc.readlines():
			line = line.strip('\n')  #去掉列表中每一个元素的换行符
			parts = line.split(" ")

			key = parts[0]
			first = parts[1]
			second = parts[2]

			src_pairs.append([key, first, second])

	#print(src_pairs, len(src_pairs))
	#print("="*100+"\n"*5)

	'''
	āáǎà    ōóǒò    êń
	ēéěè    īíǐì    ň   [ňg]
	ūúǔù    ǖǘǚǜ    ü  [ǹ]
	'''

	with open(os.path.join(folder_path, "zh_symbol.utf8"), "w") as fTgt:

		src_pairs = find_and_replace(src_pairs, "a", ["ā","á","ǎ","à","a"], r"a([a-z]*)[1-5]", fTgt)
		#print(src_pairs, len(src_pairs))

		src_pairs = find_and_replace(src_pairs, "e", ["ē","é","ě","è","e"], r"e([a-z]*)[1-5]", fTgt)
		#print(src_pairs, len(src_pairs))

		src_pairs = find_and_replace(src_pairs, "o", ["ō","ó","ǒ","ò","o"], r"o([a-z]*)[1-5]", fTgt)
		#print(src_pairs, len(src_pairs))

		src_pairs = find_and_replace(src_pairs, "i", ["ī","í","ǐ","ì","i"], r"i([a-z]*)[1-5]", fTgt)
		#print(src_pairs, len(src_pairs))

		src_pairs = find_and_replace(src_pairs, "u", ["ū","ú","ǔ","ù","u"], r"u([a-z]*)[1-5]", fTgt)
		#print(src_pairs, len(src_pairs))

		src_pairs = find_and_replace(src_pairs, "v", ["ǖ","ǘ","ǚ","ǜ","ü"], r"v([a-z]*)[1-5]", fTgt)
		print(src_pairs, len(src_pairs))
